/*
 * Copyright (C) 2015 Kenji Le
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package glamourbeautyclinic;

import images.GlamourImage;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import util.DBConnection;

/**
 *
 * @author Kenji Le
 */
public class FrmLogin extends javax.swing.JInternalFrame {
    
    GlamourImage GI = new GlamourImage();
    DBConnection dc;
    ArrayList param = new ArrayList();
    
    /**
     * Creates new form FrmLogin
     */
    public FrmLogin(DBConnection dc) {
        initComponents();
        this.dc = dc;
        GI.addIconFor(this);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((screenSize.width - this.getWidth()) / 2, (screenSize.height - this.getHeight()-60) / 2);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblUser = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();
        lblPass = new javax.swing.JLabel();
        txtPass = new javax.swing.JPasswordField();
        btnSubmit = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setTitle("Login");
        setToolTipText("");

        lblUser.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblUser.setForeground(new java.awt.Color(0, 51, 255));
        lblUser.setText("Username");

        txtUser.setForeground(new java.awt.Color(0, 102, 51));
        txtUser.setText("admin");

        lblPass.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblPass.setForeground(new java.awt.Color(0, 51, 255));
        lblPass.setText("Password");

        txtPass.setForeground(new java.awt.Color(0, 102, 51));
        txtPass.setText("123");

        btnSubmit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnSubmit.setForeground(new java.awt.Color(0, 51, 51));
        btnSubmit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Submit.png"))); // NOI18N
        btnSubmit.setText("Submit");
        btnSubmit.setBorderPainted(false);
        btnSubmit.setContentAreaFilled(false);
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        btnCancel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancel.setForeground(new java.awt.Color(0, 51, 51));
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/quit.png"))); // NOI18N
        btnCancel.setText("Cancel");
        btnCancel.setBorderPainted(false);
        btnCancel.setContentAreaFilled(false);
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblPass, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblUser, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel)))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUser)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPass)
                    .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSubmit)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        if (checkLogin()) {
            setAuthority();
            this.dispose();
        }
    }//GEN-LAST:event_btnSubmitActionPerformed

    private boolean checkLogin(){
        
        String sql = "SELECT * FROM Account WHERE UserName = ? AND Password = ?";
        param.clear();
        param.add(txtUser.getText());
        param.add(new String(txtPass.getPassword()));
        dc.rs = dc.prepareSelect(dc.preSt_Login, sql, param);
        try {
            if (dc.rs.next()) {
                if ( dc.rs.getBoolean("Active")==true) {
                    JOptionPane.showMessageDialog(this, "Log in successfully.");
                    return true;
                } else {
                    JOptionPane.showMessageDialog(this, "Your account is locked. Contact administrator for more detail.");
                    return false;
                }
            } else {
                JOptionPane.showMessageDialog(this, "Wrong Username or Password. Try again.");
                return false;
            }
        } catch (SQLException ex) {
            Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
    
    private void setAuthority() {
        Field varUser, varRole;
        Method setText, setEnabledJMenu, setEnabledJMenuItem;
        String role;
        try {
            role = dc.rs.getString("Role");
            varUser = getDesktopPane().getTopLevelAncestor().getClass().getDeclaredField("user");
            varUser.set(getDesktopPane().getTopLevelAncestor(), txtUser.getText());
            varRole = getDesktopPane().getTopLevelAncestor().getClass().getDeclaredField("role");
            varRole.set(getDesktopPane().getTopLevelAncestor(), role);
            setText = getDesktopPane().getTopLevelAncestor().getClass().getMethod("setText", String.class, String.class);
            setEnabledJMenu = getDesktopPane().getTopLevelAncestor().getClass().getMethod("setEnabledJMenu", String.class, boolean.class);
            setEnabledJMenuItem = getDesktopPane().getTopLevelAncestor().getClass().getMethod("setEnabledJMenuItem", String.class, boolean.class);
            
            setText.invoke(getDesktopPane().getTopLevelAncestor(), "lblUserDetail", txtUser.getText());
            setText.invoke(getDesktopPane().getTopLevelAncestor(), "lblRoleDetail", dc.rs.getString("Role"));
            setText.invoke(getDesktopPane().getTopLevelAncestor(), "lblLoginAtDetail", new SimpleDateFormat("MM-dd-yyyy hh:mm:ss").format(new Date()));
            
            setEnabledJMenuItem.invoke(getDesktopPane().getTopLevelAncestor(), "mniChangePass", true);
            setEnabledJMenuItem.invoke(getDesktopPane().getTopLevelAncestor(), "mniLogOut", true);
            setEnabledJMenuItem.invoke(getDesktopPane().getTopLevelAncestor(), "mniLogIn", false);
            
            switch (role) {
                case "Administrator":
                    setEnabledJMenuItem.invoke(getDesktopPane().getTopLevelAncestor(), "mniMaAcc", true);
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuCust", true);
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuSer", true);
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuPer", true);
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuCash", true);
                    break;
                case "Customer":
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuCust", true);
                    break;
                case "Service":
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuSer", true);
                    break;
                case "Personel":
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuPer", true);
                    break;
                case "Cashier":
                    setEnabledJMenu.invoke(getDesktopPane().getTopLevelAncestor(), "mnuCash", true);
                    break;
            }
            
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | SQLException ex) {
            Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JLabel lblPass;
    private javax.swing.JLabel lblUser;
    private javax.swing.JPasswordField txtPass;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
}
